<template>
  <div class="p-30">
    <div class="titlebox">账号管理</div>
    <div>
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <!-- **********************基本资料*********************** -->
        <el-tab-pane label="基本资料" name="basedata">
          <div class="basedatabox">
            <el-descriptions :border="true" class="margin-top" title="基本资料" :column="1">
              <el-descriptions-item>
                <template #label>
                  <div class="cell-item">
                    <el-icon>
                      <Postcard />
                    </el-icon>
                    账号
                  </div>
                </template>
                {{ account }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <div class="cell-item">
                    <el-icon>
                      <User />
                    </el-icon>
                    姓名
                  </div>
                </template>
                {{ username }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <div class="cell-item">
                    <el-icon>
                      <iphone />
                    </el-icon>
                    手机号
                  </div>
                </template>
                {{ userInfo.mobile }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-tab-pane>

        <!-- **********************我的头像*********************** -->
        <el-tab-pane label="我的头像" name="avatar">
          <div class="avatartab">
            <el-avatar shape="square" :size="260" fit="cover" :src="avatar" />
            <div class="avatarEdit">
              <el-upload ref="uploadRef" class="upload-demo" name="imgFile" v-model:file-list="fileList"
                :show-file-list="false" :action="uploadUrl" :auto-upload="false" :before-upload="beforeAvatarUpload"
                :on-success="uploadSuccess" :on-change="handleFileChange" :on-error="onError" :on-exceed="onExceed">
                <div class="avatar-preview avatarbox">
                  <img v-if="previewUrl" :src="previewUrl" class="avatar avatar-preview" />
                  <div class="mask" v-else>
                    <el-icon class="iconstyle">
                      <Plus />
                    </el-icon>
                  </div>
                </div>
              </el-upload>

              <!-- 编辑和保存按钮 -->
              <div class="m-t-10">点击头像编辑</div>
              <el-button class="m-t-10" type="success" @click="submitUpload"> 保存修改 </el-button>
            </div>
          </div>
        </el-tab-pane>

        <!-- **********************密码管理*********************** -->
        <el-tab-pane label="密码管理" name="password">
          <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules"
            label-width="auto" class="demo-ruleForm">
            <el-form-item label="旧密码" prop="oldpass">
              <el-input v-model="ruleForm.oldpass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="新密码" prop="pass">
              <el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPass">
              <el-input v-model="ruleForm.checkPass" type="password" autocomplete="off" />
            </el-form-item>

            <el-form-item class="btnbox">
              <el-button type="primary" @click="submitForm(ruleFormRef)"> 提交修改 </el-button>
              <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, inject, computed, watch, onMounted } from 'vue'

import { useRouter } from 'vue-router'
const router = useRouter()

// 引入网络请求相关
import api from '@/request/api'
const axios = inject('axios')

// 加载user模块 以及底下变量
import { storeToRefs } from 'pinia'
import useStore from '@/store'
const { user } = useStore()
let { username, avatar, userInfo, uid, account } = storeToRefs(user)

// 设置初始tab栏
const activeName = ref('basedata')

// 后端文件上传地址
let uploadUrl = ref('https://api.gzzxue.com/shop115/uploadfile')

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const previewUrl = ref('')
const uploadRef = ref(null)

let fileList = ref([])
watch(fileList, (newX) => {
  // 监测文件列表变化 只取最后一个文件上传（避免冗余图片上传到服务器）
  fileList.value.splice(0, fileList.value.length - 1)
})

onMounted(async () => {
  console.log(username.value, userInfo.value)
})

// tab栏切换
const handleClick = (tab, event) => {
  //   console.log(tab, event)
}

// 头像上传成功 回调
function uploadSuccess(a, b, c) {
  console.log(a, b, c)
  updateUserAvatar(a.data.img)
}

function onError(err) {
  console.log(err)
  showMessage('error', '')
}

function onExceed() {
  showMessage('error', '上传数量超出')
}

// 文件上传前的检查
const beforeAvatarUpload = (file) => {
  const isJPG = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp'].includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 5
  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG PNG GIF BMP 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 5MB!')
  }

  return isJPG && isLt2M
}

// 文件选择后的处理 （实现头像预览）
const handleFileChange = (file, ownfileList) => {
  if (!file.raw) {
    return
  }
  const reader = new FileReader() // 关键的FileReader
  reader.onload = (e) => {
    previewUrl.value = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

// 手动调用 提交到服务器
const submitUpload = () => {
  console.log(uploadRef);

  uploadRef.value.submit()
}

// 设置修改用户头像
async function updateUserAvatar(avatarUrl) {
  let data = {
    uid: uid.value,
    img: avatarUrl
  }
  console.log(data)

  let res = await axios.post(api.setavatar, data)

  console.log(res)
  if (res.code == 0) {
    showMessage('success', '头像修改成功')
    // 更新用户数据
    let info = await axios.post(api.myinfo, { uid: uid.value })
    console.log(info)
    if (info.code == 0) {
      // 更对象的某个属性 利用传入方法的方式修改
      user.$patch((state) => {
        state.userInfo.avatar = info.data.avatar
      })
    } else {
      showMessage('error', '头像数据更新失败')
    }
  }
}

// 信息提示
const showMessage = (msgtype, msgstr) => {
  ElMessage({
    showClose: true,
    message: msgstr,
    type: msgtype
  })
}

/* ********************************以下为密码修改JS************************************* */
const ruleFormRef = ref(null)

const checkAge = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('Please input the age'))
  }
  setTimeout(() => {
    if (!Number.isInteger(value)) {
      callback(new Error('Please input digits'))
    } else {
      if (value < 18) {
        callback(new Error('Age must be greater than 18'))
      } else {
        callback()
      }
    }
  }, 1000)
}

const validatePass = (rule, value, callback) => {
  if (value === '') {
    // Please input the password
    callback(new Error('请输入新密码'))
  } else {
    if (ruleForm.checkPass !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('checkPass')
    }
    callback()
  }
}
const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    // Please input the password again
    callback(new Error('请输入确认密码'))
  } else if (value !== ruleForm.pass) {
    callback(new Error('确认密码不一致!'))
  } else {
    callback()
  }
}

const validateOldpass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('旧密码不能为空！'))
  } else {
    callback()
  }
}

const ruleForm = reactive({
  oldpass: '',
  pass: '',
  checkPass: '',
  age: ''
})

const rules = reactive({
  oldpass: [{ validator: validateOldpass, trigger: 'blur' }],
  pass: [{ validator: validatePass, trigger: 'blur' }],
  checkPass: [{ validator: validatePass2, trigger: 'blur' }],
  age: [{ validator: checkAge, trigger: 'blur' }]
})

const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      console.log('submit!')
      console.log(ruleForm)
      let updatePwd = await axios.post(api.changepassword, {
        uid: uid.value,
        passwordold: ruleForm.oldpass,
        passwordnew: ruleForm.checkPass
      })
      if (updatePwd.code == 0) {
        showMessage('success', updatePwd.msg)
        logout()
      } else {
        showMessage('error', updatePwd.msg)
      }
    } else {
      console.log('error submit!')
    }
  })
}

// 退出登录
function logout() {
  // 清除用户数据
  user.$patch((state) => {
    state.userInfo = {}
    state.logindata = {}
  })

  router.replace({
    name: 'Login'
  })
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped>
.basedatabox {
  width: 700px;
}

/* 基本资料表格 */
.itemtable {
  width: 90px !important;
}

.titlebox {
  font-size: 26px;
  font-weight: 500;
  margin-bottom: 20px;
}

.demo-tabs>.el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.avatartab {
  display: flex;
  align-items: center;
}

.avatarEdit {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-left: 80px;
}

.avatarbox {
  position: relative;
}

.avatar {
  object-fit: cover;
}

.avatar-preview,
.mask {
  width: 150px;
  height: 150px;
  border-radius: 50%;
}

.mask {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.6);
}

.editicon {
  display: none;
}

.mask:hover .editicon {
  display: block;
}

.iconstyle {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #fff;
  font-size: 35px;
}

/* ****************密码管理**************** */
.demo-ruleForm {
  padding-top: 30px;
}

.btnbox {
  margin-left: 70px;
  margin-top: 40px;
}
</style>
